import json

import datetime
from django import http
from django.db import transaction
from django.views import View
from django.http import JsonResponse

from utils.views import LoginRequiredJSONMixin

from homes.models import House
from order.models import Order

# 添加订单
class Create_pyment(LoginRequiredJSONMixin, View):

    def post(self, request):

        user = request.user
        # 提取参数
        data_dict = json.loads(request.body.decode())
        house_id = data_dict.get("house_id")
        start_date = data_dict.get("start_date")
        end_date = data_dict.get("end_date")

        # 参数校验
        if not all([house_id, start_date, end_date]):
            return http.JsonResponse({
                "errno": 400,
                "errmsg": "缺少必选参数"
            })


        with transaction.atomic():

            save_id = transaction.savepoint()

            # 业务处理　
            """判断房源表中是否有用户传递过来的房源的信息　如果有就将该房源信息添加到
            　当前用户对应的　订单表内
            """
            try:
                # 获取当前用户需要添加的房源s
                house = House.objects.get(pk=house_id)

            except Exception as e:
                return http.JsonResponse({
                    "errno": 400,
                    "errmsg": "没有能选择的该房源信息"
                })

            days = datetime.datetime.strptime(end_date,'%Y-%m-%d') - datetime.datetime.strptime(start_date,'%Y-%m-%d')
            if days.days < 0:
                return JsonResponse({'errno':400,'errmsg':'时间错误'})

            # 假如说该房屋id 已经在订单表呢 　说明已经预定了
            if house.id in Order.house_id:

                transaction.savepoint_rollback(save_id)

                return http.JsonResponse({
                    "errno":"400",
                    "errmsg":"该房屋已经被预定"
                })

            # 获取当前用户的订单表 的所有订单信息
            order =Order.objects.create(
                house_id=house_id,
                user_id=user.id,
                begin_date=start_date,
                end_date=end_date,
                days=days.days,
                house_price = house.price,
                amount = house.price * days.days,

            )
            # 提交保存点（删除保存点）
            transaction.savepoint_commit(save_id)


            # 返回结果
            return http.JsonResponse({
                "data": {
                    "order_id": order.id
                },
                "errno": "0",
                "errmsg": "订单添加成功"
            })

    def get(self, request):
        # 提取参数
        role = request.GET.get("role")
        user = request.user

        # 参数校验
        if not role:
            return http.JsonResponse({
                "errno": "400",
                "errmsg": "缺少必传参数"
            })

        # 定义一个空列表
        orders = []

        """业务处理 用户判断"""
        # 用户为 房客
        if role == "custom":
            try:
                # 获取当前用户所有关联的房源订单
                orders1 = Order.objects.filter(user_id=user.id).order_by('-pk')
            except Exception as e:
                return http.JsonResponse({
                    "errno": 400,
                    "errmsg": "该用户没有订单房源信息"
                })

            # 遍历每一个房源信息
            for order in orders1:
                # 每遍历一个房源对象就在订单列表orders　
                # 中追加一个详细房源信息 order.to_dict()
                orders.append(order.to_dict())

        # 用户为 房东
        elif role == "landlord":
            try:
                # 获取当前用户所有关联的房源订单
                houses = House.objects.filter(user_id=user.id)
                house_ids = [ house.id for house in houses]
                orders1 = Order.objects.filter(house_id__in=house_ids).order_by('-pk')
            except Exception as e:
                print(e)
                return http.JsonResponse({
                    "errno": 400,
                    "errmsg": "该用户没有订单房源信息"
                })

            # 遍历每一个房源房源信息
            for order in orders1:
                # 每遍历一个房源对象就在订单列表orders　
                # 中追加一个详细房源信息 order.to_dict()
                orders.append(order.to_dict())

        # 追终返回对应用户的数据

        return http.JsonResponse({
            "errno": "0",
            "errmsg": "OK",
            "data":{
                "orders":orders,
            }
        })



# 接单和拒单
class OrderStatusView(View):
    def put(self,requset,order_id):
        # 获取用户登陆
        user = requset.user
        # 获取参数
        date = json.loads(requset.body.decode())
        action = date.get('action')

        if action not in ('accept','reject'):
            return JsonResponse({
                'code':400,
                'errmsg':'缺少必要参数'
            })

        # 根据订单号查询订单，并且要求订单处于等待接单状态
        try:
            order = Order.objects.get(id=order_id,status=0)
        except Exception as e:
            return JsonResponse({'code':500,'errmsg':'无法获取订单数据'})


        if not order:
            return JsonResponse({'code':400,'errmsg':"订单不存在"})

            # 接单，将订单状态设置为等待支付
        if action == 'accept':
            order.status = 1
            order.save()
            # 拒单，要求用户传递拒单原因
        elif action == 'reject':
            reason = date.get('reason')
            if not reason:
                return JsonResponse({
                    'code':400,
                    'errmsg':'请输入理由'
                })
            order.status = 6
            order.comment =reason
            order.save()

        return JsonResponse({
            'errno':0,
            'errmsg':'操作成功'
        })


# 评价订单
class CommentView(LoginRequiredJSONMixin,View):
    def put(self,request,order_id):
        # 暂时不知道是什么传过来的参数是什么样子的
        comment = request.body.decode()
        try:
            Order.objects.get(pk=order_id).update(comment=comment)
        except Exception as e:
            print(e)
            return JsonResponse({'errno':400,'errmsg':'评论失败'})
        return JsonResponse({'errno':0,'errmsg':'评论成功'})

